package io.hepu.robotize.interceptor;

import io.hepu.robotize.config.ShiroProperties;
import io.hepu.robotize.model.Permission;
import io.hepu.robotize.util.JCollection;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 全局权限拦截器，通过匹配URI
 */
@Component
public class AuthzInterceptor implements HandlerInterceptor {
    private static final Logger LOG = LoggerFactory.getLogger(AuthzInterceptor.class);

    @Resource
    private ShiroProperties shiroProperties;

    @Override
    public boolean preHandle(HttpServletRequest req, @NonNull HttpServletResponse resp, @NonNull Object handler) throws Exception {
        String uri = req.getServletPath();
        LOG.debug("Checking permissions for URI: {}", uri);
        List<Permission> permissions = shiroProperties.getPermissions();
        // 查找当前请求的权限
        Permission permission = JCollection.find(permissions, p -> uri.startsWith(p.getUri())).orElse(null);
        if (null != permission) {
            boolean isPermitted = SecurityUtils.getSubject().isPermitted(permission.getCode());
            if (isPermitted) {
                LOG.debug("Access allowed for URI: {}, permission: {}", uri, permission.getCode());
                return true;
            } else {
                LOG.warn("Access denied for URI: {}, permission: {}", uri, permission.getCode());
                WebUtils.toHttp(resp).sendError(HttpServletResponse.SC_FORBIDDEN, "用户无相关权限");
                return false;
            }
        }
        // 如果没有找到匹配的权限，默认允许访问
        LOG.debug("No specific permission required for URI: {}", uri);
        return true;
    }
}
